package com.zcfeng.ischool;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import Xlist.XListView;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import utils.MyConstaints;
import utils.SPUtils;
import utils.TreeViewAdapter_2;

public class CommunityActivity extends AppCompatActivity   implements XListView.IXListViewListener {
    private List<TreeViewAdapter_2.TreeNode> treeNode;
    private Handler mHandler;
    private Handler talkingHandler;
    private Handler requestmHandler;
    private TreeViewAdapter_2 adapter;
    boolean fresh=true;
    XListView list=null;
    MyApp app;
    ExpandableListView.OnChildClickListener stvClickEvent = new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                                    int groupPosition, int childPosition, long id) {
            Intent intent =new Intent(getApplicationContext(),TextActivity.class);
            Bundle bundle=new Bundle();
            TreeViewAdapter_2.TreeNode node=treeNode.get(groupPosition);
            intent.putExtras(bundle) ;
           switch(groupPosition){
               case 1:
                   if(childPosition+1==adapter.getChildrenCount(groupPosition))
                   {
                       fresh=false;
                       JSONObject json=new JSONObject();
                       try {
                           json.put("type","get");
                           json.put("option","request");
                           json.put("start",adapter.getChildrenCount(groupPosition)-1);
                           String str=json.toString();
                           Message msg=new Message();
                           msg.what= MyConstaints.send;
                           msg.obj=str;
                           app.socket.revHandler.sendMessage(msg);
                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                   }
                   else{
                       RongIM.getInstance().startPrivateChat(CommunityActivity.this,node.childs.get(childPosition).get("sponsor"),node.childs.get(childPosition).get("sponsor"));
                   }

                   break;
               case 0:

                   if(childPosition+1==adapter.getChildrenCount(groupPosition))
                   {
                       fresh=false;
                       JSONObject json=new JSONObject();
                       try {
                           json.put("type","get");
                           json.put("option","chat");
                           json.put("start",adapter.getChildrenCount(groupPosition)-1);
                           String str=json.toString();
                           Message msg=new Message();
                           msg.what= MyConstaints.send;
                           msg.obj=str;
                           app.socket.revHandler.sendMessage(msg);
                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                   }
                   else {
                       String roomid = node.childs.get(childPosition).get("roomid");
                       RongIM.getInstance().startConversation(CommunityActivity.this, Conversation.ConversationType.CHATROOM, roomid, node.childs.get(childPosition).get("content") + "\n" + node.childs.get(childPosition).get("description"));//(CommunityActivity.this,"888",);
                   }
                   }


            return false;
        }
    };
    public String[] groups = { "话题","活动" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_community);
        app= (MyApp) getApplication();
        initview();
        init_handler();
        app.addHandle(MyConstaints.get,mHandler);
        app.addHandle(MyConstaints.talking,talkingHandler);
        app.addHandle(MyConstaints.request,requestmHandler);
        list.setXListViewListener(this);
        list.setOnChildClickListener(stvClickEvent);
        getlist();
    }

    private void initview() {
        list=(XListView)findViewById(R.id.xListView);
        adapter=new TreeViewAdapter_2(getApplicationContext(),38);
        list.setAdapter(adapter);
        treeNode=adapter.getTreeNode();
    }

    private void getlist() {
        JSONObject json=new JSONObject();
        try {
            fresh=true;
            json.put("type","get");
            json.put("option","fresh");
            json.put("id", SPUtils.getString(getApplicationContext(), MyConstaints.ID,""));
            String str=json.toString();
            Message msg=new Message();
            msg.what= MyConstaints.send;
            msg.obj=str;
            app.socket.revHandler.sendMessage(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void init_handler() {
        mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String str=msg.obj.toString();
                refresh(str);
            }
        };
        talkingHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String str=msg.obj.toString();
                try {
                    JSONObject job=new JSONObject(str);
                    RongIM.getInstance().startConversation(CommunityActivity.this, Conversation.ConversationType.CHATROOM, job.getString("room"), job.getString("title") + "\n" + job.getString("description"));//(CommunityActivity.this,"888",);
                } catch (JSONException e) {

                }
            }
        };
        requestmHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String str=msg.obj.toString();
                try {
                    JSONObject job=new JSONObject(str);
                    RongIM.getInstance().startConversation(CommunityActivity.this, Conversation.ConversationType.CHATROOM, job.getString("room"), job.getString("title") + "\n" + job.getString("description"));//(CommunityActivity.this,"888",);
                    RongIM.getInstance().startPrivateChat(CommunityActivity.this,job.getString("sponsor"),job.getString("sponsor"));
                } catch (JSONException e) {

                }


            }
        };
    }

    private void refresh(String str) {
        if(fresh) {
            treeNode.clear();
            for (int i = 0; i < 2; i++) {
                TreeViewAdapter_2.TreeNode node = new TreeViewAdapter_2.TreeNode();
                node.parent = groups[i];
                treeNode.add(node);
            }
        }
        try {
            System.out.println(str);
            JSONObject jsonObject=new JSONObject(str);
            Iterator it=jsonObject.keys();
            while (it.hasNext()){
                String ss= (String) it.next();
                System.out.println(ss);

                JSONArray ob= (JSONArray) jsonObject.get(ss);
                for (int i=0;i<ob.length();i++){
                    JSONObject jso= (JSONObject) ob.getJSONObject(i);
                    HashMap<String,String> hmp=new HashMap<>();
                    int index=0;
                    index=0;
                    switch(ss){
                        case "chat":
                            hmp.put("content",jso.getString("title"));
                            hmp.put("date",jso.getString("date"));
                            hmp.put("roomid",jso.getString("roomid"));
                            hmp.put("description",jso.getString("description"));
                            treeNode.get(0).childs.add(hmp);
                            break;
                        case "request":
                            hmp.put("sponsor",jso.getString("sponsor"));
                            hmp.put("date",jso.getString("date"));
                            hmp.put("content",jso.getString("title"));
                            hmp.put("place",jso.getString("place"));
                            treeNode.get(1).childs.add(hmp);
                    }
                }
                fresh=false;
            }
            adapter.updateTreeNode(treeNode);
           adapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void add(View v){
        PopupMenu pm=new PopupMenu(this,v);
        pm.getMenuInflater().inflate(R.menu.comm_menu,pm.getMenu());
        pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getTitle().toString())
                {
                    case "发一个话题":
                        AA();
                        break;
                    case "发出一个活动":
                        BB();
                        break;
                }

                return false;
            }
        });
        pm.show();
        //pm.show();
    }

    private void AA() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.event_aa,
                (ViewGroup) findViewById(R.id.dialog));
        final EditText title= (EditText) layout.findViewById(R.id.title);
        final EditText description= (EditText) layout.findViewById(R.id.desc);
        new AlertDialog.Builder(this).setTitle("发起一个讨论").setView(layout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Message msg=new Message();
                        JSONObject json=new JSONObject();
                        try {
                            json.put("type","talking");
                            json.put("id", SPUtils.getString(getApplicationContext(), MyConstaints.NAME,""));
                            json.put("title",title.getText());
                            json.put("description",description.getText());
                            String str=json.toString();
                            msg.what= MyConstaints.send;
                            msg.obj=str;
                            app.socket.revHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        getlist();
                    }
                })
                .setNegativeButton("取消", null).show();


    }
    private void BB() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.event_bb,
                (ViewGroup) findViewById(R.id.dialog));
        final EditText title= (EditText) layout.findViewById(R.id.title);
        final EditText place= (EditText) layout.findViewById(R.id.desc);
        new AlertDialog.Builder(this).setTitle("发出一个请求").setView(layout)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Message msg=new Message();
                        JSONObject json=new JSONObject();
                        try {
                            json.put("type","request");
                            json.put("id", SPUtils.getString(getApplicationContext(), MyConstaints.NAME,""));
                            json.put("title",title.getText());
                            json.put("place",place.getText());
                            String str=json.toString();
                            msg.what= MyConstaints.send;
                            msg.obj=str;
                            app.socket.revHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        getlist();
                    }
                })
                .setNegativeButton("取消", null).show();


    }
    @Override
    public void onRefresh() {
        SPUtils.putBoolean(getApplicationContext(),"fresh",true);
        getlist();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.setRefreshTime("刚刚");
                list.stopRefresh();
                list.stopLoadMore();
            }
        }, 2000);

    }

    @Override
    public void onLoadMore() {

    }
    public void  back(View v){
        finish();

    }
}
